#!/usr/bin/env python3.11
# -*- coding: utf-8 -*-

import requests
from datetime import datetime, timedelta  # Import timedelta here
import pytz
from timezonefinder import TimezoneFinder
import time
import subprocess
from astral import LocationInfo 
from astral.sun import sun
from suntime import Sun, SunTimeException
import os
def get_sunrise_sunset(latitude, longitude,date=None):
    # 如果没有指定日期，使用当前日期
    if date is None:
        date = datetime.now().strftime('%Y-%m-%d')
    
    url = f"https://api.sunrise-sunset.org/json?lat={latitude}&lng={longitude}&date={date}&formatted=0"
    # url = f"https://api.sunrise-sunset.org/json?lat={latitude}&lng={longitude}&formatted=0"
    response = requests.get(url,timeout=10)
    data = response.json()
    # print(data)
    if response.status_code == 200 and data['status'] == 'OK':
        return data['results']['sunrise'], data['results']['sunset']
    else:
        raise Exception("Error fetching data from the API.")

def format_time(utc_time, timezone):
    # local_time = utc_time.astimezone(pytz.timezone(timezone))
    return utc_time.strftime("%Y-%m-%d %H:%M")

def is_daylight_saving(local_time, timezone):
    # Determine if the given local time is in daylight saving time
    tz = pytz.timezone(timezone)
    localized_time = tz.localize(local_time)
    return int(localized_time.dst() != timedelta(0))

def get_utc_offset(timezone_str,current_date):
    # 定义纽约时区
    ny_tz = pytz.timezone(timezone_str)

    # 将日期时间对象关联到纽约时区
    ny_dt = ny_tz.localize(current_date)

    # 获取UTC偏移（%z）
    utc_offset = ny_dt.strftime("%z")
    # 提取小时和分钟的偏移
    sign = -1 if utc_offset[0] == '-' else 1
    hours_offset = int(utc_offset[1:3])
    minutes_offset = int(utc_offset[3:5])

    # 计算总偏移小时，考虑符号
    total_offset_hours = sign * (hours_offset + minutes_offset / 60)
    return total_offset_hours

def adjust_for_dst(time, dst):
    """Adjust the time for DST if needed."""
    if dst:
        # 通常是将时间提前一个小时
        time -= timedelta(hours=1)
    return time

def exe_sun_set_compare(city,latitude,longitude,sunrise_utc,sunset_utc,timezone_str,current_date):
    sunrise = format_time(sunrise_utc, timezone_str)
    sunset = format_time(sunset_utc, timezone_str)
    # Create the local timezone datetime objects 2025-10-16 05:56:00 2025-10-15 17:23:00
    sunrise_time = datetime.fromisoformat(sunrise)
    sunset_time = datetime.fromisoformat(sunset)
    # 以日升时间获取夏令时
    dst = is_daylight_saving(current_date, timezone_str)

    # 夏令时校准
    # if dst:
    #     sunrise_time -= timedelta(hours=1)
    #     sunset_time -= timedelta(hours=1)
    # 以日升时间获取UTC时差
    offset = get_utc_offset(timezone_str,current_date)
    # Format times to string if necessary
    adjusted_sunrise = sunrise_time.time().isoformat()
    adjusted_sunset = sunset_time.time().isoformat()

    args = f"{city} {latitude} {longitude} {offset} {sunrise[:4]} {sunrise[5:7]} {sunrise[8:10]} {dst} {adjusted_sunrise} {adjusted_sunset}"
    result = subprocess.run(["./sun"] + args.split(), check=True, text=True, capture_output=True)

    col = result.stdout.split("|")
    sunrise_diff = abs(int(col[4]))
    sunset_diff = abs(int(col[7]))
    # print(f"{city} {latitude} {longitude} GMT:{offset} current:{current_date} rise:{sunrise} set:{sunset} DST:{dst} {adjusted_sunrise} {adjusted_sunset}")
    # 筛选差值较大的数据
    if (sunrise_diff > 10 or sunset_diff > 10):
        print(f"{city} {latitude} {longitude} GMT:{offset} current:{current_date} rise:{sunrise} set:{sunset} DST:{dst} {adjusted_sunrise} {adjusted_sunset}")
        print(f"dst:{dst} | {result.stdout}",end="")
    output_path = "./output/"
    # 检查并创建目录
    os.makedirs(output_path, exist_ok=True)
    output_path = output_path + f"{current_date.year}_{current_date.month}" + ".log"
    with open(output_path, 'a', encoding='utf-8') as file:
        file.write(result.stdout)
def main():
    # Coordinates and city names (30 Chinese + other cities)
    locations = [
        ("北京", 39.9042, 116.4074),
        ("上海", 31.2304, 121.4737),
        ("广州", 23.1291, 113.2644),
        ("香港", 22.3964, 114.1095),
        ("成都", 30.5728, 104.0668),
        ("重庆", 29.5630, 106.5516),
        ("天津", 39.3434, 117.3616),
        ("杭州", 30.2741, 120.1551),
        ("南京", 32.0603, 118.7969),
        ("九龙", 22.3193, 114.1694),
        ("厦门", 24.4798, 118.0895),
        ("苏州", 31.2983, 120.5832),
        ("西安", 34.3416, 108.9398),
        ("宁波", 29.8683, 121.5440),
        ("长春", 43.8171, 125.3235),
        ("哈尔滨", 45.8038, 126.5349),
        ("青岛", 36.0671, 120.3826),
        ("汕头", 23.3790, 116.7168),
        ("佛山", 23.0267, 113.1310),
        ("沈阳", 41.8057, 123.4315),
        ("贵阳", 26.6001, 106.6520),
        ("长沙", 28.2282, 112.9388),
        ("淄博", 36.8165, 118.0590),
        ("西昌", 27.9945, 102.1679),
        ("济南", 36.673, 117.0204),
        ("深圳", 23.1008,113.3076),
        ("纽约", 40.7128, -74.0060),
        ("洛杉矶", 34.0522, -118.2437),
        ("伦敦", 51.5074, -0.1278),
        ("巴黎", 48.8566, 2.3522),
        ("东京", 35.6895, 139.6917),
        ("旧金山", 37.7749, -122.4194),
        ("莫斯科", 55.7558, 37.6173),
        ("新加坡", 1.3521, 103.8198),
        ("柏林", 52.5200, 13.4050),
        ("悉尼", -33.8688, 151.2093),
        ("罗马", 41.9028, 12.4964),
        ("孟买", 19.0760, 72.8777),
        ("圣保罗", -23.5505, -46.6333),
        ("马德里", 40.4168, -3.7038),
        ("哥本哈根", 55.6761, 12.5683),
        ("斯德哥尔摩", 59.3293, 18.0686),
        ("伊斯坦布尔", 41.0082, 28.9784),
        ("雅典", 37.9838, 23.7275),
        ("里约热内卢", -22.9068, -43.1729),
        ("迪拜", 25.276987, 55.296249),
    ]

    tf = TimezoneFinder()
    # 此处在夏令时情况下：比如纽约3月9日 时间在3点前后，日升日落结果会相差一小时
    start_date = datetime(2025, 1, 1,4,0,0)
    end_date = datetime(2025, 12, 31)

    # for city, latitude, longitude in locations:
    #     current_date = start_date
    #     while current_date <= end_date:
    #         try:
    #             sunrise_utc, sunset_utc = get_sunrise_sunset(latitude, longitude,current_date.strftime('%Y-%m-%d'))
    #             timezone_str = tf.timezone_at(lat=latitude, lng=longitude)
    #             sunrise = format_time(datetime.fromisoformat(sunrise_utc), timezone_str)
    #             sunset = format_time(datetime.fromisoformat(sunset_utc), timezone_str)

    #             # Create the local timezone datetime objects
    #             sunrise_time = datetime.fromisoformat(sunrise)
    #             sunset_time = datetime.fromisoformat(sunset)

    #             # Check for daylight saving time
    #             dst = is_daylight_saving(sunrise_time, timezone_str)
                
    #             # Get UTC offset
    #             offset = get_utc_offset(timezone_str)
    #             # print(f"{city} {latitude} {longitude} {offset} {sunrise[:4]} {sunrise[5:7]} {sunrise[8:10]} {dst} {sunrise[11:]} {sunset[11:]}")

    #             args = f"{city} {latitude} {longitude} {offset} {sunrise[:4]} {sunrise[5:7]} {sunrise[8:10]} {dst} {sunrise[11:]} {sunset[11:]}"
    #             result = subprocess.run(["./sun"] + args.split(), check=True, text=True, capture_output=True)
    #             print(result.stdout,end="")
    #             output_path = "./output/" + f"{current_date.month}" + ".log"
    #             with open(output_path, 'a', encoding='utf-8') as file:
    #                 file.write(result.stdout)
    #             # time.sleep(1)  # Delay to avoid hitting the request limit
    #             current_date += timedelta(days=1)
    #         except Exception as e:
    #             print(f"An error occurred for {city} ({latitude}, {longitude}): {str(e)}")

    # for city, latitude, longitude in locations:
    #     current_date = start_date
    #     print(f"current {city} {latitude} {longitude}")
    #     timezone_str = tf.timezone_at(lat=latitude, lng=longitude)
    #     city_tmp = LocationInfo(latitude=latitude, longitude=longitude)
    #     while current_date <= end_date:
    #         try:
    #             s = sun(city_tmp.observer, date=current_date,tzinfo=pytz.timezone(timezone_str))
    #             sunrise_utc =  s['sunrise']
    #             sunset_utc = s['sunset']
    #             exe_sun_set_compare(city,latitude,longitude,sunrise_utc,sunset_utc,timezone_str,current_date)
    #             current_date += timedelta(days=1)
    #         except Exception as e:
    #             print(f"An error occurred for {city} {current_date} ({latitude}, {longitude}): {str(e)}")
    #             current_date += timedelta(days=1)

    for city, latitude, longitude in locations:
        current_date = start_date
        print(f"current {city} {latitude} {longitude}")
        timezone_str = tf.timezone_at(lat=latitude, lng=longitude)
        # 创建一个Sun对象
        sun = Sun(latitude, longitude)
        while current_date <= end_date:
            try:
                # 获取日出的当地时间
                sunrise_utc = sun.get_local_sunrise_time(current_date,pytz.timezone(timezone_str))
                # 获取日落的当地时间
                sunset_utc = sun.get_local_sunset_time(current_date,pytz.timezone(timezone_str))
                exe_sun_set_compare(city,latitude,longitude,sunrise_utc,sunset_utc,timezone_str,current_date)
                current_date += timedelta(days=1)
            except Exception as e:
                print(f"An error occurred for {city} {current_date} ({latitude}, {longitude}): {str(e)}")
                current_date += timedelta(days=1)


if __name__ == "__main__":
    main()